package com.chlvip.demo.redisson.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.redisson.spring.session.config.EnableRedissonHttpSession;
import org.redisson.spring.transaction.RedissonTransactionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 * redisson缓存
 */
@Configuration
@EnableCaching
@EnableRedissonHttpSession(maxInactiveIntervalInSeconds = 18000)
public class RedissonConfig {

    /**
     * redisson客户端
     */
    @Bean(destroyMethod = "shutdown")
    RedissonClient redisson(@Value("classpath:/redisson.json") Resource configFile) throws IOException {
        Config config = Config.fromJSON(configFile.getInputStream());
        return Redisson.create(config);
    }

    /**
     * spring 缓存管理器
     */
    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        return new RedissonSpringCacheManager(redissonClient, "classpath:/cache-config.json");
    }

    /**
     * spring 事务管理器
     */
    @Bean
    public RedissonTransactionManager redissonTransactionManager(RedissonClient redisson) {
        return new RedissonTransactionManager(redisson);
    }

    /**
     * session 确定者
     */
    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return new CookieHttpSessionIdResolver();
    }

    /**
     * jcache 缓存管理器
     */
//    @Bean
    public javax.cache.CacheManager jCacheManager(RedissonClient redisson) throws URISyntaxException {
        MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
//        Configuration<String, String> config = RedissonConfiguration.fromInstance(redisson, jcacheConfig);
        return Caching.getCachingProvider().getCacheManager();
    }
}
